/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shaman.dialog.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Shaman
 */
public class ExtensionFileFilter extends FileFilter {

    List<String> extensions;
    String description = null;

    public static String getPatternByFilemask(String mask)
    {
        String Special = "[](){}\\^$.|?*+";
        String regex = "";
        for (int i = 0; i < mask.length(); i++)
        {
            if (mask.charAt(i) == '*')
                regex += ".*";
            else if (mask.charAt(i) == '?')
                regex += ".";
            else if (mask.charAt(i) == ';')
                regex += "|";
            else if (Special.contains(String.valueOf(mask.charAt(i))))
                regex += "\\"+String.valueOf(mask.charAt(i));
            else
                regex += String.valueOf(mask.charAt(i));
        }
        return regex;
    }

    public ExtensionFileFilter(String desc, String[] exts)
    {
        description = desc;
        extensions = new ArrayList<String>();
        for (int i = 0; i < exts.length; i++)
            extensions.add(exts[i]);
    }

    public ExtensionFileFilter(String desc, String ext)
    {
        description = desc;
        extensions = new ArrayList<String>();
        extensions.add(ext);
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String getDescription() {
        if (description != null && !description.isEmpty())
            return description;
        else
        {
            if (!extensions.isEmpty())
            {
                String desc = "Files (";
                for (String ext : extensions)
                    desc += "*."+ext;
                desc += ")";
                return desc;
            }
            else
            {
                return "All files";
            }
        }
    }

    public List<String> getExtensions() {
        return extensions;
    }

    public void addExtension(String ext)
    {
        extensions.add(ext);
    }

    @Override
    public boolean accept(File f) {
        if (f.isDirectory())
            return true;
        if (!extensions.isEmpty())
        {
            for (String ext : extensions)
            {
                if (f.getName().endsWith("."+ext))
                    return true;
            }
            return false;
        }
        return true;
    }

}
